import { Rule, popMsg } from './Rule'
import { Log } from '../../utils/log'
/**
 * 长度校验
 */
export class LengthRule implements Rule {
  async validate(val: any, rule: any, form: any): Promise<boolean> {
    if (!val) {
      return true
    }
    if (val instanceof Array) {
      Log.error('此校验规则不支持数组类型忽略', val)
      return true;
    }
    if (rule['type'] && rule['type'] === 'number') {
      if (Number.isNaN(val)) {
        let value = val + ''
        return this.validateStr(value, rule)
      } else {
        let value = val * 1
        return this.validateNum(value, rule)
      }
    } else {
      let value = val + ''
      return this.validateStr(value, rule)
    }
  }

  validateNum(val: number, rule: any) {
    if (rule['max'] && val > rule['max']) {
      popMsg(rule['errorMessage'])
      return false
    }
    if (rule['min'] && val < rule['min']) {
      popMsg(rule['errorMessage'])
      return false
    }
    return true
  }

  validateStr(val: string, rule: any) {
    if (rule['max'] && val.length > rule['max']) {
      popMsg(rule['errorMessage'])
      return false
    }
    if (rule['min'] && val.length < rule['min']) {
      popMsg(rule['errorMessage'])
      return false
    }
    return true
  }
}